package com.chen.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chen.service.IAccount;
import com.chen.entity.Account;
import com.chen.mapper.AccountMapper;
import lombok.extern.slf4j.Slf4j;
import org.dromara.hmily.annotation.HmilyTCC;
import org.dromara.hmily.common.exception.HmilyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;

@Service
@Slf4j
public class AccountImpl extends ServiceImpl<AccountMapper, Account> implements IAccount {
    @Resource
    private AccountMapper accountMapper;

    @Override
    @HmilyTCC(confirmMethod = "commitTransOut",cancelMethod = "cancelTransOut")
    @Transactional(rollbackFor = HmilyException.class)
    public void transOut(int accountId, BigDecimal amount) throws Exception {
        //检查
        Account account = getById(accountId);
        if (account == null){
            throw new HmilyException("转出账户不存在");
        }
        if (account.getAmount().compareTo(amount) == -1){
            throw new HmilyException("账户余额不足");
        }
        //冻结转出资金
        freezeAmount(account,amount);
    }

    private void freezeAmount(Account account, BigDecimal amount) {
        account.setAmount(account.getAmount().subtract(amount));
        account.setFrozenAmount(account.getFrozenAmount()==null?amount:account.getFrozenAmount().add(amount));
        updateById(account);
    }


    public void commitTransOut(int accountId, BigDecimal amount){
        log.info("执行service1-commit");
        accountMapper.transferOut(accountId,amount);
    }

    public void cancelTransOut(int accountId, BigDecimal amount){
        log.error("执行service1-cancel");
        accountMapper.unfreezeAmount(accountId,amount);
    }
}
